package com.dartfar.workflow.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.HistoryService;
import org.jbpm.api.ProcessDefinitionQuery;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.ProcessInstanceQuery;
import org.jbpm.api.RepositoryService;
import org.jbpm.api.TaskQuery;
import org.jbpm.api.TaskService;
import org.jbpm.api.history.HistoryTask;
import org.jbpm.api.history.HistoryTaskQuery;
import org.jbpm.api.model.OpenProcessInstance;
import org.jbpm.api.task.Participation;
import org.jbpm.api.task.Task;
import org.jbpm.pvm.internal.history.model.HistoryTaskImpl;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ProcessDefinitionImpl;
import org.jbpm.pvm.internal.model.TransitionImpl;
import org.jbpm.pvm.internal.task.TaskImpl;
import org.springframework.stereotype.Component;

import com.dartfar.base.dao.DaoUtil;
import com.dartfar.base.model.BaseEntity;
import com.dartfar.base.model.Person;
import com.dartfar.base.model.Role;
import com.dartfar.util.DateUtils;
import com.dartfar.util.EntityUtils;
import com.dartfar.util.StringUtils;
import com.dartfar.workflow.constant.StringVeriable;
import com.dartfar.workflow.constant.WorkflowCaleType;
import com.dartfar.workflow.constant.WorkflowDeployVar;
import com.dartfar.workflow.constant.WorkflowEventType;
import com.dartfar.workflow.constant.WorkflowStatusVar;
import com.dartfar.workflow.constant.WorkflowTradeType;
import com.dartfar.workflow.model.WorkflowEvents;
import com.dartfar.workflow.model.WorkflowProcessFunMount;
import com.dartfar.workflow.model.WorkflowTaskFunMount;
import com.dartfar.workflow.vo.WorkflowCurUserTasksVo;
import com.dartfar.workflow.vo.WorkflowExecuteTaskVo;

@Component("workflowTaskService")
public class WorkflowTaskServiceImpl implements WorkflowTaskService {

	static Logger logger = Logger.getLogger(WorkflowTaskServiceImpl.class);
	
	@Resource
	private TaskService taskService;
	@Resource
	private RepositoryService repositoryService;
	@Resource
	private ExecutionService executionService;
	@Resource
	private HistoryService historyService;
	@Resource
	private WorkflowPermissionService workflowPermissionService;
	@Resource
	private WorkflowEventsService workflowEventsService;
	
	@Resource
	private DaoUtil<Role> roleDaoUtil;
	@Resource
	private DaoUtil<Person> personDaoUtil;
	@Resource
	private DaoUtil<BaseEntity> baseEntityDaoUtil;
	@Resource
	private DaoUtil<WorkflowProcessFunMount> workflowProcessFunMountDaoUtil;
	
	
	/**
	 * 得到当前登陆人的所有活动节点
	 * @param person
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@Override
	public List<WorkflowCurUserTasksVo> getCurrentUserTask(Person person, int pageNo, int pageSize) {
		// TODO Auto-generated method stub
		//String currentUserCode=LoginInfoUtil.currentUserCode;
		
		String personId = String.valueOf(person.getPersonId());
		
		if(!StringUtils.isNotEmpty(personId)){
			logger.error("未登录.");	
			return new ArrayList<WorkflowCurUserTasksVo>();
		}
		//查询JBPM当前登录人的任务信息   执行任务
		List<Task> tasks = taskService.createTaskQuery().assignee(personId).list();
		List<WorkflowCurUserTasksVo> curTasks = new ArrayList<WorkflowCurUserTasksVo>();
		//构建任务节点的集合
		buildCurTasks(curTasks, tasks);
		//如果当前需要的记录没有超过start+limit
		logger.info("curTasks Size : " + curTasks.size());
		//如果curTasks 不等于 0
		if(curTasks.size() >= 0){
			pageNo = (pageNo-1) * pageSize;
			if(curTasks.size() <= (pageNo + pageSize)){
				//拿需要处理的任务。   登陆人作为候选人
				List<Task> caleTasks = taskService.createTaskQuery().candidate(personId).list();
				logger.info("caleTasks: " + caleTasks.size());
				buildCurTasks(curTasks, caleTasks);
			}
			//根据分页返回指定集合
			pageSize = pageNo + pageSize;
			if(pageSize >= curTasks.size()){
				pageSize = curTasks.size();
			}
			curTasks=curTasks.subList(pageNo, pageSize);
		}

		return curTasks;
	}
	
	/**
	 * 构建任务节点的集合
	 * @param taskJobs
	 * @param tasks
	 */
	public void buildCurTasks(List<WorkflowCurUserTasksVo> taskJobs, List<Task> tasks){
		for(Task task : tasks){
			WorkflowCurUserTasksVo wcutv = new WorkflowCurUserTasksVo();
			wcutv.setTaskId(task.getId());
			wcutv.setTaskName(task.getName());
			wcutv.setCreateTime(DateUtils.formatDateTime(task.getCreateTime()));
			//查询当前流程实例的全局变量
			Set<String> paramNames = new HashSet<String>();
			paramNames.add(WorkflowDeployVar.BO_ID_VALUE);
			paramNames.add(WorkflowDeployVar.BO_ID_NAME);
			paramNames.add(WorkflowDeployVar.BO_TYPE);
			paramNames.add(WorkflowDeployVar.BO_URL);
			//全局变量。  根据任务节点ID
			Map<String, Object> variables = taskService.getVariables(task.getId(), paramNames);
			String modelName = (String) variables.get(WorkflowDeployVar.BO_TYPE);
			wcutv.setModelName(modelName);
			String url = (String) variables.get(WorkflowDeployVar.BO_URL);
			wcutv.setUrl(url);
			String modelIdName = (String) variables.get(WorkflowDeployVar.BO_ID_NAME);
			logger.info("modelIdName: "+ modelIdName);
			wcutv.setModelIdName(modelIdName);
			Integer idValue = (Integer)variables.get(WorkflowDeployVar.BO_ID_VALUE);
			wcutv.setIdValue(idValue.toString());
			Class clazz = null;
			try {
				clazz = Class.forName(modelName);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//得到业务对象
			BaseEntity entity = (BaseEntity)baseEntityDaoUtil.get(idValue, clazz);
			//pcManagerTemplate.findById(clazz, idValue);
			if(EntityUtils.isNotNull(entity)){
				//String pdid=entity.getPdid();
				//String piid=entity.getPiid();
				String processInstanceId = entity.getProcessInstanceId();
				wcutv.setProcessId(String.valueOf(entity.getPersonId()));
				wcutv.setProcessDefinitionId(entity.getProcessDefinitionId());
				//job.setPdid(pdid);
				wcutv.setProcessName(processInstanceId.substring(0, processInstanceId.indexOf(".")));
				//job.setProcessName(piid.substring(0,piid.indexOf(".")));
				wcutv.setAssigne(task.getAssignee());
				//job.setAssigne(task.getAssignee());
				taskJobs.add(wcutv);
			}
		}
	}

	/**
	 * 执行任务
	 * @param wetVo
	 * @param returnObj
	 */
	@Override
	public void execTasks(Person person, WorkflowExecuteTaskVo wetVo, JSONObject returnObj) {
		// TODO Auto-generated method stub
		if (EntityUtils.isNotNull(wetVo) && StringUtils.isNotEmpty(wetVo.getModelName())
				&& StringUtils.isNotEmpty(wetVo.getModelId())) {
			//活动节点
			TaskImpl task = (TaskImpl) taskService.getTask(wetVo.getTaskId());
			
			logger.info("taskName: " + task.getName());
			
			if (EntityUtils.isNotNull(task)) {
				Class calzz = null;
				try {
					calzz = Class.forName(wetVo.getModelName());
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					logger.error(wetVo.getModelName() + " 实例化失败.");
					e.printStackTrace();
					return;
				}
				BaseEntity entity = baseEntityDaoUtil.get(Integer.valueOf(wetVo.getModelId()).intValue(), calzz);
				//pcManagerTemplate.findById(calzz, wfTaskInfoVo.getModelId());
				if (EntityUtils.isNotNull(entity)) {
					//拿到当前登陆人
					String curPersonId = String.valueOf(person.getPersonId());
					if (!StringUtils.isNotEmpty(curPersonId)) {
						logger.error("未登录.");
					}
					// 完成任务
					//得到当前任务节点的流出转移名称
					Set<String> outcomes = taskService.getOutcomes(wetVo.getTaskId());
					
					logger.info("outcomes: " + outcomes.size());
					
					//是否可以回退
					String isRollbackable = (String) taskService.getVariable(wetVo.getTaskId(),WorkflowDeployVar.ROLLBACKABLE);
					logger.info("isRollbackable: " + isRollbackable);
					//是否可以取回
					String isWithdrawable = (String) taskService.getVariable(wetVo.getTaskId(),WorkflowDeployVar.WITHDRAWABLE);
					logger.info("isWithdrawable: " + isWithdrawable);
					//加载我的流出转移
					if (StringUtils.isNotEmpty(isRollbackable) && !isRollbackable.equalsIgnoreCase(StringVeriable.STR_FALSE)) {
						logger.info("如果没有回退路径。");
						// 如果没有回退路径，动态加载路径
						if (!outcomes.contains(wetVo.getSubmitType()) && WorkflowTradeType.ROLLBACK.equalsIgnoreCase(wetVo.getSubmitType())) {
							//加载流程转移
							buildRollbackTrade(task);
							//加入到流程转移名称中
							outcomes.add(WorkflowTradeType.ROLLBACK);
						}
					}
					
					if (StringUtils.isNotEmpty(isWithdrawable) && !isWithdrawable.equalsIgnoreCase(StringVeriable.STR_FALSE)) {
						logger.info("如果没有取回路径。");
						// 如果没有收回路径，动态加载路径
						if (!outcomes.contains(wetVo.getSubmitType()) && WorkflowTradeType.WITHDRAW.equalsIgnoreCase(wetVo.getSubmitType())) {
							buildPreStepWithdraw(task);
							outcomes.add(WorkflowTradeType.WITHDRAW);
						}
					}
					
					logger.info("查到流转路径。");
					logger.info("SUBMITTYPE： " + wetVo.getSubmitType());
					logger.info("SUBMITTYPE： " + WorkflowTradeType.SUBMIT);
					
					// 如果已查到流转路径，可以执行任务
					if (StringUtils.isNotEmpty(wetVo.getSubmitType()) && outcomes.contains(wetVo.getSubmitType())) {
						//如果是回退操作
						if (WorkflowTradeType.ROLLBACK.equalsIgnoreCase(wetVo.getSubmitType())) { /***/
							logger.info("这是回退操作.");
							execBackTask(wetVo, task, entity, curPersonId,returnObj);
							//doRollBack(wetVo,task,entity, curPersonId,returnObj);
						} else
						//如果是送交操作
						if (WorkflowTradeType.SUBMIT.equalsIgnoreCase(wetVo.getSubmitType())) {
							logger.info("这是提交操作.");
							execSendTask(wetVo, task, entity, curPersonId, returnObj);
							//doNextNode(wetVo, task, entity, curPersonId, returnObj);
						} else
						//如果是取回操作
						if (WorkflowTradeType.WITHDRAW.equalsIgnoreCase(wetVo.getSubmitType())) {
							logger.info("这是取回操作.");
							execReturnTask(wetVo, task, entity, curPersonId, returnObj);
							//doCallBack(wetVo, task, entity, curPersonId, returnObj);
						} else
						//如果是归档操作
						if (WorkflowTradeType.END.equalsIgnoreCase(wetVo.getSubmitType())) {
							logger.info("这是归档操作.");
							execSendTask(wetVo, task, entity, curPersonId, returnObj);
							//doNextNode(wetVo, task, entity, curPersonId, returnObj);
						}
					}
				} else {
					logger.error("业务实体获取失败.");
				}
			}else{
				logger.error("任务获取失败.");
			}
		}
	}
	
	/**
	 * 构建取回路径操作
	 * @param task
	 */
	private void buildPreStepWithdraw(TaskImpl task) {
		// TODO Auto-generated method stub
		//得到回退的节点名称  也就是上一个节点名称
		String rollbackTaskName = (String) task.getVariable(WorkflowDeployVar.ROLLBACKTASKNAME);
		String pdid = task.getProcessInstance().getProcessDefinitionId();
		ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
		ProcessDefinitionImpl pd = (ProcessDefinitionImpl) query.processDefinitionId(pdid).uniqueResult();
		//得到目标节点对象
		ActivityImpl toActivityImpl = pd.findActivity(rollbackTaskName);
		//得到本节点对象
		ActivityImpl fromActivityImpl = task.getExecution().getActivity();
		// 创建取回路径
		TransitionImpl newTran = fromActivityImpl.createOutgoingTransition();
		newTran.setName(WorkflowTradeType.WITHDRAW);
		newTran.setDestination(toActivityImpl);
		fromActivityImpl.addOutgoingTransition(newTran);
	}
	
	/**
	 * 构建回退路径操作
	 * @param task
	 */
	private void buildRollbackTrade(TaskImpl task) {
		// TODO Auto-generated method stub
		//拿到流程实例
		OpenProcessInstance pi = task.getProcessInstance();
		String pid = pi.getProcessDefinitionId();
		//得到流程定义对象
		ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
		ProcessDefinitionImpl pd = (ProcessDefinitionImpl) query.processDefinitionId(pid).uniqueResult();
		//拿到当前任务的活动节点对象
		ActivityImpl fromActivityImpl = task.getExecution().getActivity();
		if ("task".equalsIgnoreCase(fromActivityImpl.getType())) {
			//得到回退目标的节点名称
			String rollbackTaskName = (String) task.getVariable(WorkflowDeployVar.ROLLBACKTASKNAME);
			if (StringUtils.isNotEmpty(rollbackTaskName)) {
				ActivityImpl toActivityImpl = pd.findActivity(rollbackTaskName);
				//创建流程转移对象
				TransitionImpl tran = fromActivityImpl.createOutgoingTransition();
				String tranName = WorkflowTradeType.ROLLBACK;
				tran.setName(tranName);
				tran.setDestination(toActivityImpl);
				//加入流程转移
				fromActivityImpl.addOutgoingTransition(tran);
			} else {
				logger.error("回退任务名称为空,创建路径失败.");
			}
		} else {
			logger.error("不是任务节点,创建路径失败.");
		}
	}
	
	/**
	 * 构建提交的信息 主要将回退和取回信息存入全局变量
	 * @param task
	 * @return
	 */
	private String buildSubmitInfo(TaskImpl task) {
		String rollbackAssignee = task.getAssignee();
		String rollbackTaskName = task.getName();
		Map<String, String> params = new HashMap<String, String>();
		// 任务的上一步
		params.put(WorkflowDeployVar.ROLLBACKUSER, rollbackAssignee);
		params.put(WorkflowDeployVar.ROLLBACKTASKNAME, rollbackTaskName);
		params.put(WorkflowDeployVar.WITHDRAWUSER, rollbackAssignee);
		taskService.setVariables(task.getId(), params);
		return rollbackAssignee;
	}
	
	/**
	 * 执行领取任务
	 * @param person
	 * @param taskId
	 * @param returnObj
	 */
	@Override
	public void execTakeTask(Person person, String taskId, JSONObject returnObj) {
		// TODO Auto-generated method stub
		//当前登录人
		String personId = String.valueOf(person.getPersonId());
		if (StringUtils.isNotEmpty(personId)) {
			Task task = taskService.getTask(taskId);
			if (EntityUtils.isNotNull(task)) {
				if (StringUtils.isNotEmpty(task.getAssignee())) {
					returnObj.put("message", "此任务已经被人领取!");
					logger.info("此任务已经被人领取。");
				} else {
					//领取任务
					taskService.takeTask(taskId, personId);
					returnObj.put("message", "任务领取成功!");
					logger.info("任务领取成功。");
				}
			} else {
				returnObj.put("message", "任务已经完成!");
				logger.info("任务已经完成。");
			}
		}
	}
	
	/**
	 * 执行送交操作
	 * @param wetVo
	 * @param task
	 * @param entity
	 * @param curPersonId
	 * @param returnObj
	 */
	public void execSendTask(WorkflowExecuteTaskVo wetVo, TaskImpl task, BaseEntity entity, String curPersonId, JSONObject returnObj) {
		// TODO Auto-generated method stub
		String oldAssignee = task.getAssignee(); // 当前任务指定人
		//得到委托信息
		String assigneType = wetVo.getAssigneType();
		String assignees = wetVo.getAssignees();
		String roles = wetVo.getRoles();
		//将回退和取回信息存入全局变量
		buildSubmitInfo(task);
		// 提交之前事件队列触发
		WorkflowTaskFunMount taskFunMount = workflowPermissionService.findWorkflowTaskFunMount(task.getProcessInstance().getProcessDefinitionId(), task.getName());
			//wfInfoManager.findTaskFunMount(task.getProcessInstance().getProcessDefinitionId(), task.getName());
		List<WorkflowEvents> taskEvents = taskFunMount.getWorkflowEvents();
		if(EntityUtils.isNotNull(taskEvents) && taskEvents.size()>0){
			for(WorkflowEvents taskEvent : taskEvents){
				if(taskEvent.getEventType().equalsIgnoreCase(WorkflowEventType.SEND_BEFORE)){
					logger.debug("这里执行自定义方法, 发送之前");
					//workflowEventsService
					//wfEventManager.executeEventMethod(taskEvent, entity);
				}
			}
		}
		//完成任务
		taskService.addTaskComment(wetVo.getTaskId(), wetVo.getComments());
		taskService.completeTask(wetVo.getTaskId(), wetVo.getSubmitType());
		//执行提交后的事件队列
		if(EntityUtils.isNotNull(taskEvents) && taskEvents.size()>0){
			for(WorkflowEvents taskEvent : taskEvents){
				if(taskEvent.getEventType().equalsIgnoreCase(WorkflowEventType.SEND_AFTER)){
					logger.debug("这里执行自定义方法, 发送之前");
					//wfEventManager.executeEventMethod(taskEvent, entity);
				}
			}
		}
		// 为历史任务日志写入执行人
		//historyService.createHi
		HistoryTaskQuery htQuery = historyService.createHistoryTaskQuery();
		htQuery.taskId(wetVo.getTaskId());
		HistoryTaskImpl htask = (HistoryTaskImpl) htQuery.uniqueResult();
		htask.setAssignee(oldAssignee);
		String piid = entity.getProcessInstanceId();
		String pdid = entity.getProcessDefinitionId();
		ProcessInstanceQuery piQuery = executionService.createProcessInstanceQuery();
		ProcessInstance pi = piQuery.processInstanceId(piid).uniqueResult();
		// 如果无后续任务，则状态为ENDED（已结束）
		if (null == pi) {
			// 如果未在工作流表中查到此实例，则意味此流程已经结束
			entity.setWorkflowStatus(WorkflowStatusVar.END_STATUS);
			returnObj.put("status", WorkflowStatusVar.END_STATUS);
			WorkflowProcessFunMount processFunMount = (WorkflowProcessFunMount) workflowProcessFunMountDaoUtil.get("from WorkflowProcessFunMount w where w.processDefinitionId = '" + pdid + "'");
			//执行流程结束事件队列
			List<WorkflowEvents> processEvents = processFunMount.getWorkflowEvents();
			if(EntityUtils.isNotNull(processEvents) && processEvents.size()>0){
				for(WorkflowEvents processEvent : processEvents){
					if(processEvent.getEventType().equalsIgnoreCase(WorkflowEventType.PROCESS_END)){
						logger.debug("这里执行自定义方法, 流程结束");
						//wfEventManager.executeEventMethod(processEvent, entity);
					}
				}
			}
		}else{
			/**---------------非常重要------------------- */
			TaskQuery tq = taskService.createTaskQuery();
			// 查询所有活动节点 改动
			//没有执行人的条件
			tq.unassigned();
			tq.processInstanceId(task.getProcessInstance().getId());
			List<Task> list = tq.list();
			if (null != list && list.size()>0) {
				/**没有执行人的情况*/
				// 如果还有后续任务，则状态为WAIT（处理中）
				if(!entity.getWorkflowStatus().equalsIgnoreCase(WorkflowStatusVar.WAIT_STATUS)){
					entity.setWorkflowStatus(WorkflowStatusVar.WAIT_STATUS);
					baseEntityDaoUtil.update(entity);
					//pcManagerTemplate.update(entity);
				}
				returnObj.put("status", WorkflowStatusVar.WAIT_STATUS);
				for (Task newTask : list) {
					// 如果是直接指定执行人
					if (WorkflowCaleType.CALE_ASSIGNE.equalsIgnoreCase(assigneType)) {
						if (StringUtils.isNotEmpty(assignees)) {
							logger.info("这是指定执行人。");
							newTask.setAssignee(assignees);
						}
					}
					// 如果委托给人。
					if (WorkflowCaleType.CALE_USER.equalsIgnoreCase(assigneType)) {//zsp,yg
						String[] assigneeArray = assignees.split(StringVeriable.STR_SPLIT);
						if (null != assigneeArray && 0 != assigneeArray.length) {
							logger.info("这是委托给人。");
							// 如果多选情况下只选中了一个候选人，则直接设置为执行人
							//if (1 == assigneeArray.length) {
							//	newTask.setAssignee(assigneeArray[0]);
							//} else {
								for (String candidate : assigneeArray) {
									//加入候选人
									taskService.addTaskParticipatingUser(newTask.getId(), candidate,Participation.CANDIDATE);
								}
							//}
						}
					}
					// 如果委托给角色
					if (WorkflowCaleType.CALE_ROLE.equalsIgnoreCase(assigneType)) {
						logger.info("这是委托给角色。");
						String[] roleArray = roles.split(StringVeriable.STR_SPLIT);
						for (String roleId : roleArray){
//							EndUser user =(EndUser) pcManagerTemplate.getEntityByHql("from EndUser where userCode = '"+ roleCode + "'");
//									System.out.println("添加了候选人"+user.getUserCode());
								taskService.addTaskParticipatingUser(newTask.getId(), roleId, Participation.CANDIDATE);
						}
							
					}
					
					String rollbackable = (String) ((TaskImpl) newTask)
							.getVariable(WorkflowDeployVar.ROLLBACKABLE);
					if (rollbackable.equalsIgnoreCase(StringVeriable.STR_TRUE)) {
						Map<String, String> params = new HashMap<String, String>();
						// 任务的上一步
//						params.put(WfVarDeploy.ROLLBACKUSER, oldAssignee);
//						params.put(WfVarDeploy.WITHDRAWUSER, oldAssignee);
//						params.put(WfVarDeploy.ROLLBACKTASKNAME,task.getName());
//						taskService.setVariables(newTask.getId(), params);
						buildRollbackTrade((TaskImpl)newTask);
					}
				}
			} else {
				List<Task> lists = taskService.createTaskQuery().processInstanceId(task.getProcessInstance().getId()).list();
 				if (null != lists && 0 != lists.size()) {
					for (Task newTask : lists) {
						if (StringUtils.isNotEmpty(newTask.getAssignee())) {
							String assignee = newTask.getAssignee();
							logger.info("assignee: " + assignee);
							if (assignee.indexOf("@") == 0) {  
								// 表示指定了角色，将候选人直接赋值给它
								newTask.setAssignee(null);
								assignee = assignee.replace("@", "'");// %rjkfb%,%ssb%
								String hql = "from Role r where r.roleId in (" + assignee + ")";
								List<Role> ros = roleDaoUtil.getList(hql);
								logger.info("rosSize: " + ros.size());
								//pcManagerTemplate.queryByHql(hql);
								if (EntityUtils.isNotNull(ros) && ros.size() > 0) {
									for(Role ro : ros){
										Set<Person> persons = (Set<Person>) ro.getPersons();
									//Set<EndUser> users = ro.getUsers();
									//Iterator<EndUser> userItor = users.iterator();
										Iterator<Person> personList = persons.iterator();
										while (personList.hasNext()) {
											Person person = personList.next();
										//EndUser user = userItor.next();
											taskService.addTaskParticipatingUser(newTask.getId(), String.valueOf(person.getPersonId()), Participation.CANDIDATE);
										//taskService.addTaskParticipatingUser(newTask.getId(),user.getUserCode(),Participation.CANDIDATE);
										}
									}
								}
							}else if(assignee.indexOf("%") == 0){
							// 表示指定了多个候选人，直接指定的userCode 
								newTask.setAssignee(null);
								assignee = assignee.replace("%", "'"); //%zsp%,%yg%
								//String hql = "from EndUser where userCode in(" + assignee + ")";
								String hql = "from Person p where p.personId in(" + assignee + ")";
								List<Person> persons = personDaoUtil.getList(hql);
							//List<EndUser> users = (List<EndUser>) pcManagerTemplate.queryByHql(hql);
							//Iterator<Person> personItor = persons.iterator();
							
								for(Person person : persons){
									taskService.addTaskParticipatingUser(newTask.getId(), String.valueOf(person.getPersonId()), Participation.CANDIDATE);
								}
					
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 执行回退操作
	 * @param wetVo
	 * @param task
	 * @param entity
	 * @param curPersonId
	 * @param returnObj
	 */
	public void execBackTask(WorkflowExecuteTaskVo wetVo, TaskImpl task, BaseEntity entity, String curPersonId, JSONObject returnObj) {
		// TODO Auto-generated method stub
		//TaskFuncMount taskFunMount=wfInfoManager.findTaskFunMount(task.getProcessInstance().getProcessDefinitionId(), task.getName());
		WorkflowTaskFunMount taskFunMount = workflowPermissionService.findWorkflowTaskFunMount(task.getProcessInstance().getProcessDefinitionId(), task.getName());

		//执行回退前事件
		List<WorkflowEvents> taskEvents = taskFunMount.getWorkflowEvents();
		if(EntityUtils.isNotNull(taskEvents) && taskEvents.size()>0){
			for(WorkflowEvents taskEvent : taskEvents){
				if(taskEvent.getEventType().equalsIgnoreCase(WorkflowEventType.ROLLBACK_BEFORE)){
					logger.debug("这里执行自定义方法, 回退之前");
					//wfEventManager.executeEventMethod(taskEvent, entity);
				}
			}
		}
		/**执行回退*/
		//回退人
		String rollbackAssignee = (String) taskService.getVariable(wetVo.getTaskId(), WorkflowDeployVar.ROLLBACKUSER);
		//加入审批意见
		taskService.addTaskComment(wetVo.getTaskId(), wetVo.getComments());
		//完成任务
		taskService.completeTask(wetVo.getTaskId(), wetVo.getSubmitType());
		//执行回退后事件
		if(EntityUtils.isNotNull(taskEvents) && taskEvents.size()>0){
			for(WorkflowEvents taskEvent : taskEvents){
				if(taskEvent.getEventType().equalsIgnoreCase(WorkflowEventType.ROLLBACK_AFTER)){
					logger.debug("这里执行自定义方法, 回退之后");
					//wfEventManager.executeEventMethod(taskEvent, entity);
				}
			}
		}
		//查询出历史活动名称
		HistoryTaskQuery htQuery = historyService.createHistoryTaskQuery();
		htQuery.taskId(wetVo.getTaskId());
		HistoryTaskImpl htask = (HistoryTaskImpl) htQuery.uniqueResult();
		htask.setAssignee(curPersonId);
		TaskQuery tq = taskService.createTaskQuery();
		//有执行人的条件
		tq.unassigned();
		tq.processInstanceId(task.getProcessInstance().getId());
		List<Task> list = tq.unassigned().list();
		if (null != list && 0 != list.size()) {
			// 如果还有后续任务，则状态为WAIT（处理中）
			if(!entity.getWorkflowStatus().equalsIgnoreCase(WorkflowStatusVar.WAIT_STATUS)){
				entity.setWorkflowStatus(WorkflowStatusVar.WAIT_STATUS);
				baseEntityDaoUtil.update(entity);
			}
			returnObj.put("status", WorkflowStatusVar.WAIT_STATUS);
			for (Task newTask : list) {
				newTask.setAssignee(rollbackAssignee);
			}
		}
	}
	
	/**
	 * 执行取回任务
	 * @param wetVo
	 * @param task
	 * @param entity
	 * @param curPersonId
	 * @param returnObj
	 */
	public void execReturnTask(WorkflowExecuteTaskVo wetVo, TaskImpl task, BaseEntity entity, String curPersonId, JSONObject returnObj) {
		// TODO Auto-generated method stub
		//TaskFuncMount taskFunMount=wfInfoManager.findTaskFunMount(task.getProcessInstance().getProcessDefinitionId(), task.getName());
		WorkflowTaskFunMount taskFunMount = workflowPermissionService.findWorkflowTaskFunMount(task.getProcessInstance().getProcessDefinitionId(), task.getName());

		// 取回之前事件队列触发
		List<WorkflowEvents> taskEvents = taskFunMount.getWorkflowEvents();
		if(EntityUtils.isNotNull(taskEvents) && taskEvents.size()>0){
			for(WorkflowEvents taskEvent : taskEvents){
				if(taskEvent.getEventType().equalsIgnoreCase(WorkflowEventType.RETURN_BEFORE)){
					logger.debug("这里执行自定义方法, 取回之前");
					//wfEventManager.executeEventMethod(taskEvent, entity);
				}
			}
		}
		
		task.setAssignee(curPersonId);
		
		taskService.completeTask(wetVo.getTaskId(), wetVo.getSubmitType());
		// 取回之后事件队列触发
		if(EntityUtils.isNotNull(taskEvents) && taskEvents.size()>0){
			for(WorkflowEvents taskEvent : taskEvents){
				if(taskEvent.getEventType().equalsIgnoreCase(WorkflowEventType.RETURN_AFTER)){
					logger.debug("这里执行自定义方法, 回退之后");
					//wfEventManager.executeEventMethod(taskEvent, entity);
				}
			}
		}

		HistoryTaskQuery htQuery = historyService.createHistoryTaskQuery();
		htQuery.taskId(wetVo.getTaskId());
		HistoryTaskImpl htask = (HistoryTaskImpl) htQuery.uniqueResult();
		// 为历史任务日志写入执行人
		htask.setAssignee(curPersonId);
		TaskQuery tq = taskService.createTaskQuery();
		tq.unassigned();
		tq.processInstanceId(task.getProcessInstance().getId());
		List<Task> list = tq.unassigned().list();
		for (Task newTask : list) {
			newTask.setAssignee(curPersonId);
		}
	}
	
	/**
	 * 执行撤销任务操作
	 * @param taskId
	 * @param modelName
	 * @param idValue
	 */
	@Override
	public void execRepealTask(String taskId, String modelName, String idValue){
		// TODO Auto-generated method stub
		TaskImpl task = (TaskImpl)taskService.getTask(taskId);
		if(EntityUtils.isNotNull(task)) {
			String piid = task.getProcessInstance().getId();
			Class classz = null;
			try {
				classz = Class.forName(modelName);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				logger.error(modelName + " 实例化失败.");
				e.printStackTrace();
				return;
			}
			BaseEntity entity = baseEntityDaoUtil.get(Integer.valueOf(idValue).intValue(), classz);
			
			if(EntityUtils.isNotNull(entity) && StringUtils.isNotEmpty(entity.getProcessInstanceId())) {
				//与JBPM做脱离操作
				entity.setProcessInstanceId(null);
				entity.setProcessDefinitionId(null);
				entity.setWorkflowStatus(WorkflowStatusVar.NO_START);
				baseEntityDaoUtil.update(entity);
				//级联删除指定流程实例对象
				executionService.deleteProcessInstanceCascade(piid);
			}
		}
	}


}
